<template>
  <div class="flex h-full">
    <a-card class="mr-2 py-2 h-full" :body-style="{ height: '100%', padding: '0 8px', display: 'flex', flexDirection: 'column' }">
      <SearchComb class="w-56" placeholder="姓名/助记码/卡号/手机号/证件号码" @search="queryTabs" />
      <div class="mt-2">
        <a-radio-group v-model:value="category" button-style="solid" class="flex radio-style" @change="queryTabs(formState)">
          <a-radio-button :value="0">未执行({{ unexecuted }})</a-radio-button>
          <a-radio-button :value="1">已执行({{ executed }})</a-radio-button>
        </a-radio-group>
      </div>
      <BaseList :data-source="listDataSource" :loading="loading">
        <template #renderItem="{ item }">
          <div class="py-2 px-3" :class="patientId === item.jzbh ? 'active' : ''" @click="onSelect(item)">
            <div class="flex justify-between">
              <div class="flex items-center">
                <div class="text-base font-bold text-primary truncate w-18" :title="item.brName">
                  {{ item.brName }}
                </div>
                <span class="mx-2">{{ item.brXb }}</span>
                <span>{{ item.brAge }}</span>
              </div>
              <div class="truncate w-16">{{ item.ksmc }}</div>
            </div>
            <div class="flex justify-between pt-2">
              <div class="text-right text-grey">{{ formatDate(item.ghsj, 'YYYY-MM-DD HH:mm') }}</div>
              <LabelValue class="text-right" :width="80" :value="item.rysx" />
            </div>
          </div>
        </template>
      </BaseList>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="patientInfo" :show-insurance="true" :show-work="false" @change="onChange">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="ml-4" label="卡号" :width="140" :value="patientInfo.brId" />
            <LabelValue class="ml-4" label="科室" :width="140" :value="patientInfo.ksmc" />
            <LabelValue class="ml-4" label="类别" :width="140" :value="patientInfo.ghlb" />
            <!-- <LabelValue class="" label="过敏史" :width="280" :tooltip="true" :value="patientInfo.brGms" /> -->
            <AllergyHistory class="ml-4" :width="280" :value="patientInfo.brGms" :patient-info="patientInfo" @success="(e) => (patientInfo.brGms = e)" />
          </div>
          <div class="flex items-center">
            <LabelValue class="ml-4" label="门诊号" :width="140" :value="patientInfo.jzbh" />
            <LabelValue class="ml-4" label="医生" :width="140" :value="patientInfo.empName" />
            <LabelValue class="ml-4" label="时间" :width="200" :value="patientInfo.ghsj" />
          </div>
        </div>
      </PatientInfoHeader>
      <a-card class="mt-2 w-full flex-1">
        <div class="mb-3 text-right">
          <a-button type="primary" @click="onCarryAll"> 审核 </a-button>
          <a-button class="ml-2" @click="onClickRecord"> 修改记录 </a-button>
        </div>
        <BaseTable
          :loading="loading"
          column-code="000325"
          :row-selection="rowSelection"
          :data-source="tableData"
          row-key="id"
          fill
          :pagination="false"
          :scroll="{ x: 2320 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'ypmc'">
              <MedicineInfo :value="{ mc: record.mc, gg: record.gg, cj: record.cj }" />
            </template>
            <!-- 状态 0：待皮试 1：皮试中 2：待审核 3：已审核 4：已过期 -->
            <template v-if="column.dataIndex === 'status'">
              <a-tag v-if="record.status === '0'" color="blue">待皮试</a-tag>
              <a-tag v-if="record.status === '1'" color="blue">皮试中</a-tag>
              <a-tag v-if="record.status === '2'" color="blue">待审核</a-tag>
              <a-tag v-if="record.status === '3'" color="success">已审核</a-tag>
              <a-tag v-if="record.status === '4'" color="red">已过期</a-tag>
            </template>
            <!-- 皮试结果 0:阴性 1：弱阳性 2:阳性 3：强阳性 -->
            <template v-if="column.dataIndex === 'result'">
              <a-tag v-if="record.result === 0" color="blue">阴性</a-tag>
              <a-tag v-if="record.result === 1" color="red">弱阳性</a-tag>
              <a-tag v-if="record.result === 2" color="red">阳性</a-tag>
              <a-tag v-if="record.result === 3" color="red">强阳性</a-tag>
            </template>
            <template v-if="column.dataIndex === 'dw'">
              {{ record.zxdw }}
            </template>
            <template v-if="column.dataIndex === 'action'">
              <template v-if="record.status === '0'">
                <a-button type="link" size="small" @click="saveResultStatus(record, '1')"> 开始皮试 </a-button>
              </template>
              <template v-if="record.status === '1'">
                <a-button type="link" size="small" danger @click="onClickResults(record)"> 结束皮试 </a-button>
                <!-- <BaseButton confirm-text="结束皮试？" type="text" danger size="small" @click="onClickResults(record)">结束皮试</BaseButton> -->
              </template>
              <template v-if="record.status === '2' || record.status === '3' || record.status === '4'">
                <a-button type="link" size="small" @click="onClickResults(record)"> 皮试结果 </a-button>
              </template>
              <template v-if="record.status === '2'">
                <a-divider type="vertical" />
                <a-button type="link" size="small" @click="saveResultStatus(record, '3')"> 审核 </a-button>
              </template>
              <template v-if="record.status === '3'">
                <a-divider type="vertical" />
                <BaseButton confirm-text="确认撤审？" type="text" danger size="small" @click="revokeResult(record)">撤审</BaseButton>
              </template>
            </template>
          </template>
        </BaseTable>
      </a-card>
    </div>
    <Edit v-model:open="openResult" :row-data="rowData" @success="getListQuantity()" />
    <Record v-model:open="openRecord" :row-data="listInfo" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import SearchComb from '@/components/SearchComb'
import { formatDate } from '@/utils/format'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import BaseList from '@/components/BaseList'
import Edit from './components/Edit.vue'
import Record from './components/Record.vue'

const openResult = ref(false)
const openRecord = ref(false)
const patientId = ref('')
const category = ref(0)
const unexecuted = ref(0)
const executed = ref(0)
const formState = ref({})
const listInfo = ref({})
const rowData = ref({})
// 0:待皮试，1：皮试中，2：待审核，3：已审核，4：已过期
const tableData = ref([])
const listDataSource = ref([])
const defaultCheckedKeys = ref([])

const rowSelection = ref({
  checkStrictly: true,
  selectedRowKeys: defaultCheckedKeys,
  onChange: (selectedRowKeys) => {
    defaultCheckedKeys.value = selectedRowKeys
  }
})

const patientInfo = usePatient(patientId, '门诊')
const onSelect = (item) => {
  patientId.value = item.jzbh
  listInfo.value = item
  getListQuantity()
}

const { loading, getData } = useTable({
  url: '/drugStorage/comprehenive/getKcGysCertificateList',
  formatParams: () => {
    return {
      gysbh: formState.value.gysbh
    }
  }
})

const onChange = () => {
  queryTabs(formState.value)
  onSelect(listInfo)
}
const saveResultStatus = async (data, status) => {
  const res = await post('/outp/mzhs/savePatientSkinTestResult', {
    brId: data.brId,
    id: data.id,
    status: status,
    result: data.result
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg || '操作成功')
  getListQuantity()
}
const revokeResult = async (data) => {
  const res = await post('/outp/mzhs/revokeSkinTestReview', {
    id: data.id
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg || '操作成功')
  getListQuantity()
}

//执行全部
const onCarryAll = async () => {
  if (defaultCheckedKeys.value.length <= 0) return message.warning('至少选择一项')
  const res = await post('/outp/mzhs/skinTestReview', {
    ids: defaultCheckedKeys.value
  })
  if (res.code !== 0) return
  message.success(res.msg)
  defaultCheckedKeys.value = []
  getListQuantity()
}

// 修改记录
const onClickRecord = () => {
  if (!listInfo.value.brId) return message.warning('请先选择患者')
  openRecord.value = true
}
// 皮试结果
const onClickResults = (row = {}) => {
  openResult.value = true
  rowData.value = row
}

const getListQuantity = async (params) => {
  const res = await post('/outp/mzhs/getListPatientSkinTestResultList', {
    eddate: formState.value.endDate ? formState.value.endDate : params?.endDate,
    stdate: formState.value.startDate ? formState.value.startDate : params?.startDate,
    jzbh: patientId.value
  })
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data || []
}

//左侧数据
const queryTabs = async (params) => {
  formState.value = params
  loading.value = true
  listDataSource.value = []
  const { code, data, msg } = await post('/outp/mzhs/getListPatientSkinTestResultPatients', {
    pyjm: formState.value.searchKey ? formState.value.searchKey : params?.searchKey,
    eddate: formState.value.endDate ? formState.value.endDate : params?.endDate,
    stdate: formState.value.startDate ? formState.value.startDate : params?.startDate,
    zxzt: category.value
  })
  loading.value = false
  if (code !== 0) return message.error(msg || '请求失败')
  const listData = data.sort((a, b) => a.yzzxzt - b.yzzxzt)
  listDataSource.value = listData
  if (!patientId.value && listDataSource.value.length > 0) {
    patientId.value = listData[0]?.jzbh
    listInfo.value = listData[0]
    getListQuantity()
  }
  getSkinTestCount(params)
}

// 左侧数量
const getSkinTestCount = async (params = {}) => {
  const { code, data, msg } = await post('/outp/mzhs/getListPatientSkinTestResultPatientsCount', {
    eddate: formState.value.endDate ? formState.value.endDate : params?.endDate,
    stdate: formState.value.startDate ? formState.value.startDate : params?.startDate
  })
  if (code !== 0) return message.error(msg || '请求失败')
  unexecuted.value = data?.wzx
  executed.value = data?.yzx
}

watch(
  () => patientId.value,
  (val) => {
    val && getData()
  }
)
</script>

<style lang="less" scoped>
.radio-style {
  :deep(.ant-radio-button-wrapper) {
    width: 66.4%;
    padding: 0;
    text-align: center;
  }
}
</style>
